package com.dtjd.playcoinmonkey.activities;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;

import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.DataSource;
import com.bumptech.glide.load.engine.GlideException;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.target.Target;
import com.dtjd.playcoinmonkey.MyApplication;
import com.dtjd.playcoinmonkey.R;
import com.dtjd.playcoinmonkey.bean.HttpParaBean;
import com.dtjd.playcoinmonkey.databinding.ActivityLookIconBinding;
import com.dtjd.playcoinmonkey.databinding.DialogBottomBinding;
import com.dtjd.playcoinmonkey.utils.Network;
import com.dtjd.playcoinmonkey.utils.Tools;
import com.github.dhaval2404.imagepicker.ImagePicker;
import com.google.android.material.bottomsheet.BottomSheetDialog;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;
public class LookIconActivity extends AppCompatActivity {
    private ActivityLookIconBinding binding;
    private ActivityResultLauncher<Intent> launcher;
    private String filename;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding= ActivityLookIconBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        BottomSheetDialog bottomSheetDialog=new BottomSheetDialog(this);
        @NonNull DialogBottomBinding dialog = DialogBottomBinding.inflate(getLayoutInflater());
        dialog.dialogCancel.setOnClickListener(view -> bottomSheetDialog.dismiss());
        dialog.dialogSave.setOnClickListener(view -> {
            bottomSheetDialog.dismiss();
            String path=Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).getAbsolutePath() + "/" + System.currentTimeMillis() + ".png";
            if (filename==null){
                Glide.with(this).downloadOnly().load(MyApplication.user.wb_url).listener(new RequestListener<File>(){
                    @Override
                    public boolean onLoadFailed(@Nullable GlideException e, Object model, Target<File> target, boolean isFirstResource) {
                        Tools.toast("保存失败");
                        return false;
                    }
                    @RequiresApi(api = Build.VERSION_CODES.Q)
                    @Override
                    public boolean onResourceReady(File resource, Object model, Target<File> target, DataSource dataSource, boolean isFirstResource) {
                        Tools.copyFile(resource.getAbsolutePath(),path);
                        Tools.toast("图片已保存到："+path);
                        return false;
                    }
                }).preload();
            }else {
                Tools.copyFile(getExternalCacheDir()+"icon/"+filename,path);
                Tools.toast("图片已保存到："+path);
            }
        });
        dialog.dialogChooseIcon.setOnClickListener(view -> {
            bottomSheetDialog.dismiss();
            ImagePicker.with(this).cropSquare().compress(1024).maxResultSize(1080, 1080).saveDir(getExternalCacheDir()+"icon").createIntent(intent -> {
                launcher.launch(intent);
                return null;
            });
        });
        bottomSheetDialog.setContentView(dialog.getRoot());
        binding.lookpicBack.setOnClickListener(view -> finish());
        binding.lookpicMore.setOnClickListener(view -> bottomSheetDialog.show());
        binding.lookpicIcon.setOnClickListener(view -> bottomSheetDialog.show());
        Glide.with(this).load(MyApplication.user.wb_url).placeholder(R.drawable.loading).error(R.drawable.loaderr).into(binding.lookpicIcon);
        launcher=registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), result -> {
            if (result.getResultCode() == Activity.RESULT_OK) {
                Uri uri= Objects.requireNonNull(result.getData()).getData();
                this.filename=new File(uri.getPath()).getName();
                binding.lookpicIcon.setImageURI(uri);
                List<HttpParaBean> list=new ArrayList<>();
                list.add(new HttpParaBean("nickname",MyApplication.user.wb_nickname));
                list.add(new HttpParaBean("token","token"));
                Network.upload("wbhMain/updateUserInfo", new File(getExternalCacheDir()+"icon/"+filename), list, new Callback() {
                    @Override
                    public void onFailure(@NonNull Call call, @NonNull IOException e) {
                        e.printStackTrace();
                    }
                    @Override
                    public void onResponse(@NonNull Call call, @NonNull Response response) {
                        runOnUiThread(() -> {
                            try {
                                JsonObject jo = JsonParser.parseString(Objects.requireNonNull(response.body()).string()).getAsJsonObject();
                                if (jo.get("code").getAsInt()==0){
                                    Tools.toast("更新头像成功");
                                    setResult(4,result.getData());
                                }else {
                                    Tools.toast(jo.get("datalist").getAsString());
                                }
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        });
                    }
                });
            } else if (result.getResultCode() == ImagePicker.RESULT_ERROR) {
              Tools.toast(ImagePicker.getError(result.getData()));
            }
        });
    }
}